package com.unionftech.common.base.mvp.proxy

import com.unionftech.common.base.mvp.IBaseView
import com.unionftech.common.base.mvp.annitation.InjectPresenter
import com.unionftech.common.base.mvp.impl.BaseModel
import com.unionftech.common.base.mvp.impl.BasePresenter

open class ProxyImpl(private val mView: IBaseView) : IProxy {
    private val mInjectPresenters: MutableList<BasePresenter<in IBaseView, in BaseModel>> by lazy { mutableListOf() }
    override fun bindPresenter() {
        val fields = mView.javaClass.declaredFields
        for (field in fields) {
            val injectPresenter = field.getAnnotation(InjectPresenter::class.java)
            if (injectPresenter != null) {
                try {
                    val type = field.type as Class<in BasePresenter<in IBaseView, in BaseModel>>
                    val injectPresenter =
                        type.newInstance() as BasePresenter<in IBaseView, in BaseModel>
                    injectPresenter.attach(mView)
                    field.isAccessible = true
                    field.set(mView, injectPresenter)
                    mInjectPresenters.add(injectPresenter)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    override fun unbindPresenter() {
        for (presenter in mInjectPresenters) {
            presenter.detach()
        }
        mInjectPresenters.clear()
    }

}